package com.sandking.encryption;

/*字符串 DESede(3DES) 加密*/
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class DES3 {

	private static final String Algorithm = "DESede"; // 定义 加密算法,可用
	private static final byte[] keyBytes = { 0x11, 0x22, 0x4F, 0x58,
			(byte) 0x88, 0x10, 0x40, 0x38, 0x28, 0x25, 0x79, 0x51, (byte) 0xCB,
			(byte) 0xDD, 0x55, 0x66, 0x77, 0x29, 0x74, (byte) 0x98, 0x30, 0x40,
			0x36, (byte) 0xE2 }; // 24字节的密钥

	// DES,DESede,Blowfish
	// 添加新安全算法,如果用JCE就要把它添加进去
	// Security.addProvider(new com.sun.crypto.provider.SunJCE());
	/**
	 * 加密
	 * 
	 * @param keybyte
	 * @param src
	 * @return
	 */
	public static String encryptMode(byte[] keybyte, String src) {
		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
			// 加密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.ENCRYPT_MODE, deskey);
			return new String(c1.doFinal(src.getBytes()));
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	/**
	 * 加密
	 * 
	 * @param keybyte
	 * @param src
	 * @return
	 */
	public static String encryptMode(String src) {
		return encryptMode(keyBytes, src);
	}

	/**
	 * 解密
	 * 
	 * @param keybyte
	 * @param src
	 * @return
	 */
	public static String decryptMode(byte[] keybyte, String src) {
		try {
			// 生成密钥
			SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);
			// 解密
			Cipher c1 = Cipher.getInstance(Algorithm);
			c1.init(Cipher.DECRYPT_MODE, deskey);
			return new String(c1.doFinal(src.getBytes()));
		} catch (java.security.NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		} catch (javax.crypto.NoSuchPaddingException e2) {
			e2.printStackTrace();
		} catch (java.lang.Exception e3) {
			e3.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param keybyte
	 * @param src
	 * @return
	 */
	public static String decryptMode(String src) {
		return decryptMode(keyBytes, src);
	}
}
